/*
 * @Author: Bennent_G
 * @Date: 2024-12-23 16:14:13
 * @LastEditTime: 2025-03-25 20:14:21
 * @Description:permission hook
 */

import { h } from 'vue';
import type { MenuProps } from 'ant-design-vue';
import { IconMap } from '@/utils/icons';
import { fetchPermissionByRoleMock, fetchPermissionByRole } from '@/apis/admin/permission';
import { Router, useRouter } from 'vue-router'; // 添加对 Router 类型的导入
import { useAuthStore } from '@/stores';

export type Permission = {
	id: number;
	parentId: number;
	name: string;
	title: string;
	path: string;
	icon?: string;
	isView?: boolean;
	children?: Permission[];
};

export default function usePermissionHook() {
	// 在hook内部直接引入router实例
	const modules = import.meta.glob('@/views/**/*.vue');
	const { setAuthRoutes } = useAuthStore();
	const router = useRouter(); // 引入router实例
	
	/**
	 * 获取权限路由
	 * @returns 
	 */
	const fetchAuthRoutes = async () => {
		const { data } = await fetchPermissionByRoleMock<Permission[]>();
		setAuthRoutes(data);
		addDynamicRoutes(router, data);
		return data;
	};

	/**
	 * @description: 将路径的最后一部分首字母大写
	 * 例如：/admin/systems/dictionary -> /admin/systems/Dictionary
	 * @param {string} path 需要处理的路径
	 * @returns {string} 处理后的路径
	 */
	const uppercasePathLastSegment = (path: string): string => {
		const [last] = path.split('/').slice(-1);
		return path.replace(last, last[0].toUpperCase() + last.slice(1));
	};

	/**
	 * @description: 动态添加路由
	 * @param router Vue Router 实例
	 * @param permissions 权限列表
	 */
	const addDynamicRoutes = (router: Router, permissions: Permission[]) => {
		permissions.forEach((permission) => {
			if (!router.hasRoute(permission.path) && permission.isView) {
				const moduleKey = Object.keys(modules).find((key) =>
					key.includes(uppercasePathLastSegment(permission.path))
				);
				if (!moduleKey) return;
				// 追加后台权限路由至home中的children路由中
				router.addRoute('home', {
					path: permission.path,
					name: permission.name,
					component: modules[moduleKey],
				});
			}

			// 递归处理子路由
			if (permission.children && permission.children.length > 0) {
				addDynamicRoutes(router, permission.children);
			}
		});
	};

	/**
	 * @description: format permissions
	 * @param {Permission[]} permissions
	 * @return {*}
	 */
	const formatPermissions = (permissions: Permission[]): (typeof MenuProps)['items'] => {
		return permissions.map((item) => {
			const icons = resolveIcon(item.icon);
			return {
				id: item.id.toString(),
				key: item.path,
				parentId: item.parentId.toString(),
				label: item.title,
				title: item.title,
				name: item.name,
				path: item.path,
				icon: () => (icons ? h(icons) : null),
				children: item.children ? formatPermissions(item.children) : undefined,
			};
		});
	};

	/**
	 * @description: resolve icon
	 * @param {IconType} iconName
	 * @return {*}
	 */
	const resolveIcon = (iconName: string | undefined): any => {
		if (!iconName) return IconMap.get('Menu');
		return IconMap.get(iconName) || IconMap.get('Menu');
	};

	return {
		fetchAuthRoutes,
		formatPermissions,
		addDynamicRoutes,
	};
}
